package com.my.blog.website.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Auther lxf
 * @Date 2021/1/22
 */
@Service
public class FileService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String upload(MultipartFile multipartFile, String suffix) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(
                multipartFile.getInputStream(), multipartFile.getSize(), suffix, null
        );
        return storePath.getFullPath();
    }

    public void delete(String path) {
        int groupIndex = path.indexOf("/");
        if (groupIndex > 0) {
            String groupPath = path.substring(0, groupIndex);
            String filePath = path.substring(groupIndex + 1);
            fastFileStorageClient.deleteFile(groupPath, filePath);
        } else {
            throw new RuntimeException();
        }
    }
}
